<?php

namespace App\Http\Controllers\Home;

use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Session;
use DB,Validator,Hash;

class UserController extends CommonController {

    /**
     * Display a listing of the resource.
     * 个人中心 订单页面
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request) {
        $userid = Session::get("userData")->id;
        $orders = DB::table('order')
                ->where('user_id', $userid)
                ->where("order_number", "LIKE", "%" . $request->get("keyword") . "%")
                ->orderBy('id', 'desc')
                ->orderBy('order_status', 'asc')
                ->paginate(10);
        $keyword = $request->get("keyword");
//        dd($orders);
        foreach ($orders as $order) {
            // 查询商品订单详情
            $order->details = DB::table('order_details')->where('order_number', $order->order_number)
                    ->get();
            foreach ($order->details as $s) {
                $s->goods_thumb = DB::table('goods')->where('id', $s->goods_id)->pluck('goods_thumb');
            }
        }
        $shoa = DB::table("order_details")->get();

        return view("home.user.order", compact("orders", "s", "keyword", "sa"));
    }

    /**
     * 个人中心 安全中心
     */
    public function safe() {
        $userRec = DB::table("user")->where("id", session('userData')->id)->first();
        return view("home.user.safe", compact("userRec"));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create() {
        
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request) {
        
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id) {
        // 
    }

    /**
     * 个人资料修改
     * @return type
     */
    public function edit() {
        $id = Session::get('userData')->id;
        $userRec = DB::table("user")->where("id", $id)->first();
        return view("home.user.profile", compact("userRec"));
    }

    /**
     * 执行更新个人资料
     * @param \Illuminate\Http\Request $request
     * @return type
     */
    public function update(Request $request) {
        $this->validate($request, [
            "user_email" => "email",
            "user_tel" => "regex:/^1[\d]{10}$/",
            "user_nickname" => "required",
                ], [
            "user_email.email" => "邮箱不符合规范",
            "user_tel.regex" => "手机不规范",
            "user_nickname.required" => "昵称不能为空",
            "user_tel.tel" => "手机号码不符合规范",
        ]);

        $data = $request->except("_token");
        if(strlen($data['user_pass'])>=6){
            if(!preg_match('/^[0-9a-zA-Z]{6,16}$/', $data['user_pass'])){
                return back()->with('info', '密码不合法');
            }
            $data['user_pass'] = Hash::make($data['user_pass']);
        }
        $id = Session::get('userData')->id;
        if (false !== $affectedRows = DB::table("user")->where("id", $id)->update($data)) {
            return redirect("/user/edit")->with(["info" => "操作成功"]);
        } else {
            return back()->with('info', '修改失败');
        }
    }

    public function avartar(Request $request) {

        if (!$request->hasFile("Filedata")) {
            return response()->json(["status" => 0, "info" => "没有文件提交"]);
        }

        //接受文件并转存
        $file = $request->file("Filedata");
        //重组文件名
        $suffix = $file->getClientOriginalExtension();
        $rename = date("YmdHis") . rand(1000, 9999) . "." . $suffix;
        //转存文件
        $file->move("./uploads/avartar", $rename);

        //将存储的文件信息 写入数据库
        DB::table("user")->where("id", $request->get("id"))->update(["user_avartar" => "/uploads/avartar/" . $rename]);

        $data = Session::pull("userData");
        $data->avartar = "/uploads/avartar/" . $rename;
        Session::put("userData", $data);

        //返回结果
        return response()->json(array("status" => 1, "info" => "/uploads/avartar/" . $rename));
    }

    // 发表评论
    public function comment($id)
    {
        $userid = Session::get('userData')->id;
        // 验证订单评论的合法性
        $comment = DB::table('order')->leftJoin('order_details', 'order.order_number', '=', 'order_details.order_number')
                ->where('order_details.id', $id)
                ->where('order.user_id', $userid)
                ->where('order.order_status', 1)
                ->where('order_details.order_status', '3')
                ->select(['order_details.*'])
                ->first();
        if(!$comment){
            return back()->with(['error'=>'无权评价']);
        }
        Session::put('comment', $comment);
        return view('home.user.comment');
    }
    
    // 处理评论
    public function commentAdd(Request $request)
    {
        $comment = Session::get('comment');
        $data = $request->only('comment_content','comment_score');
        $data['user_id'] = Session::get('userData')->id;
        $data['goods_id'] = $comment->goods_id;
        $data['attr_id'] = $comment->attr_id;
        $data['comment_time'] = date('Y-m-d H:i:s');
        if($data['comment_score'] < 1) $data['comment_score'] = 1;
        // 执行插入
        $res = DB::table('comment')->insert($data);
        if(false != $res){
            // 执行修改状态
            DB::table('order_details')->where('id', $comment->id)->update(['order_status'=>4]);
            Session::forget('comment');
            return redirect('/user')->with(['error'=>'评价成功']);
        } else {
            return back();
        }
    }
}
